/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.me.stepapp;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.view.View;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Amber
 */
public class ShowMap extends MapActivity {
    MapView mapView = null;
    // MapController mapController = null;
    MyLocationOverlay whereAmI = null;
    LocationManager locMan = null;
    LocationListener locLis = null;

    @Override
    protected boolean isLocationDisplayed() {
        return whereAmI.isMyLocationEnabled();
    }

    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);

        mapView = (MapView)findViewById(R.id.mapView);
        mapView.setBuiltInZoomControls(true);
        mapView.setClickable(true);

        mapView.getController().setZoom(15);

        whereAmI = new MyLocationOverlay(this, mapView);
        mapView.getOverlays().add(whereAmI);

        Drawable marker = getResources().getDrawable(R.drawable.pushpin);
        marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());

        FriendFinder myFriends = new FriendFinder(marker);
        mapView.getOverlays().add(myFriends);

        mapView.postInvalidate();

        locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locLis = new LocationListener()  {
            public void onLocationChanged(Location location) {
                showLocation(location);
            }

            public void onStatusChanged(String provider, int status, Bundle extras) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            public void onProviderEnabled(String provider) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }

            public void onProviderDisabled(String provider) {
                //throw new UnsupportedOperationException("Not supported yet.");
            }
        };
    }

    @Override
    public void onResume() {
        super.onResume();
        Location lastLoc = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        showLocation(lastLoc);
        locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locLis);
        whereAmI.enableMyLocation();
        whereAmI.runOnFirstFix(new Runnable() {
            public void run() {
                mapView.getController().setCenter(whereAmI.getMyLocation());
            }
        });
    }

    @Override
    public void onPause()  {
        super.onPause();
        locMan.removeUpdates(locLis);
        whereAmI.disableMyLocation();
    }

    private void showLocation(Location location) {
        if (location != null) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();

            GeoPoint pt = new GeoPoint((int)(lat*1E6), (int)(lng*1E6));

            Toast.makeText(getBaseContext(), "LOCATION:  Latitude[" + lat + "] Longitude[" + lng + "]", Toast.LENGTH_SHORT).show();

            mapView.getController().animateTo(pt);
        }
    }

    public void clickHandler(View target)  {
        switch(target.getId()){
            case R.id.normal:
                mapView.setSatellite(false);
                mapView.setStreetView(false);
                mapView.setTraffic(false);
                break;
            case R.id.satellite:
                mapView.setSatellite(true);
                break;
            case R.id.street:
                mapView.setStreetView(true);
                break;
            case R.id.traffic:
                mapView.setTraffic(true);
                break;
        }
    }

    //Inner class that is ItemizedOverlay of Friends Locations
    class FriendFinder extends ItemizedOverlay {
        private List<OverlayItem> friends = new ArrayList<OverlayItem>();

        private Drawable marker;

        @Override
        protected OverlayItem createItem(int i) {
            return friends.get(i);
        }

        @Override
        public int size() {
            return friends.size();
        }

       public FriendFinder(Drawable marker) {
           super(marker);

           this.marker = marker;

           GeoPoint cindy = new GeoPoint((int)(41.103158 * 1E6), (int)(-80.709699 * 1E6));
           friends.add(new OverlayItem(cindy, "Cindy", "Cindy"));

           GeoPoint apt = new GeoPoint((int)(40.460064 * 1E6), (int)(-79.932871 * 1E6));
           friends.add(new OverlayItem(apt, "Amber", "Amber"));
           
           GeoPoint joe = new GeoPoint((int)(40.460032 * 1E6), (int)(-79.932845 * 1E6));
           friends.add(new OverlayItem(joe, "Joe", "Joe"));

           GeoPoint cmu = new GeoPoint((int)(40.444769 * 1E6), (int)(-79.942973 * 1E6));
           friends.add(new OverlayItem(cmu, "CMU", "CMU"));
           /*Cursor c = getContentResolver().query(People.CONTENT_URI, null, null, null, People.NAME + " ASC");
           startManagingCursor(c);

           int notesColumn = c.getColumnIndex(People.NOTES);
           int nameColumn = c.getColumnIndex(People.NAME);
           GeoPoint p = null;

		// Moves the cursor to the first row
		// and returns true if there is sth. to get
           if (c.isFirst()) {
                do {
                    String notesString = c.getString(notesColumn);

                    Location friendLocation = null;
                        if (notesString != null) {
                        // Pattern for extracting geo-ContentURIs from the notes.

                            final String geoPattern = "(geo:[\\-]?[0-9]{1,3}\\.[0-9]{1,6}\\,[\\-]?[0-9]{1,3}\\.[0-9]{1,6}\\#)";
				// Compile and use regular expression
                            Pattern pattern = Pattern.compile(geoPattern);

                            CharSequence inputStr = notesString;
                            Matcher matcher = pattern.matcher(inputStr);

                            boolean matchFound = matcher.find();
                            if (matchFound) {
                            // We take the first match available
                                String groupStr = matcher.group(0);
                                // And parse the Lat/Long-GeoPos-Values from it
                                String strLat = groupStr.substring(groupStr.indexOf(":") + 1, groupStr.indexOf(","));
                                String strLng = groupStr.substring(groupStr.indexOf(",") + 1, groupStr.indexOf("#"));
                                Double lng = Double.parseDouble(strLng);
                                Double lat = Double.parseDouble(strLat);
                                p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
                            }
                        }
				/if(friendLocation != null && location.distanceTo(friendLocation) < maxDistance){
					String friendName = c.getString(nameColumn);
					nearFriends.add(new Friend(friendLocation, friendName));
				}/
                        String friendName = c.getString(nameColumn);
                        friends.add(new OverlayItem(p, friendName, "Hello"));
                    } while (!c.isLast());*/
                populate();
            }

        @Override
        public void draw(Canvas canvas, MapView mapView, boolean shadow) {
            super.draw(canvas, mapView, shadow);

            boundCenterBottom(marker);
        }

    }

}
